package xyz.penghaonan.p2plib.job.operations;

import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;

import xyz.penghaonan.p2plib.utils.P2PActionListener;
import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.job.base.BaseOperation;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PHelper;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PListenerAdapter;
import xyz.penghaonan.p2plib.helper.sockethelper.ClientSocketHelper;

public class ConnectServerOperation extends BaseOperation<WifiP2pInfo> {
    private WifiP2pDevice wifiP2pDevice;
    private Result<WifiP2pInfo> result = new Result<>();

    public ConnectServerOperation() {
    }

    public void setWifiP2pDevice(WifiP2pDevice wifiP2pDevice) {
        this.wifiP2pDevice = wifiP2pDevice;
    }

    @Override
    public void doOperation() {
        notifyProgress(0f, "连接设备：" + wifiP2pDevice.deviceName);
        WifiP2PHelper wifiP2PHelper = P2PManager.getP2PHelper();
        wifiP2PHelper.addListener(wifiP2PListener);
        wifiP2PHelper.connect(wifiP2pDevice, new P2PActionListener() {

            @Override
            public void onSuccess() {
                super.onSuccess();
            }

            @Override
            public void onFailure(int reason) {
                super.onFailure(reason);
            }
        });
        operationWait(60000);
        wifiP2PHelper.removeListener(wifiP2PListener);
        setResult(result);
        if (result.success) {
            ClientSocketHelper socketHelper = P2PManager.getClientSocketHelper();
            if (socketHelper != null) {
                socketHelper.postConnectToServer(result.data.groupOwnerAddress.getHostAddress());
                notifyProgress(0.5f, "创建通信管道");
            }
        }
    }

    private final WifiP2PListenerAdapter wifiP2PListener = new WifiP2PListenerAdapter() {
        @Override
        public void onConnectCallChanged(boolean isConnected) {
            super.onConnectCallChanged(isConnected);
            log("onConnectCallChanged isConnected:" + isConnected);
        }

        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
            super.onConnectionInfoAvailable(wifiP2pInfo);
            log("onConnectionInfoAvailable wifiP2pInfo:" + wifiP2pInfo);
            result.success = wifiP2pInfo != null;
            result.data = wifiP2pInfo;
            if (result.success) {
                notifyProgress(0.5f, "设备连接成功：" + wifiP2pInfo.groupOwnerAddress.getHostAddress());
            } else {
                notifyProgress(0.5f, "设备连接失败");
            }
            operationContinue();
        }

        @Override
        public void onDisConnectCallChanged(boolean isDisConnected) {
            super.onDisConnectCallChanged(isDisConnected);
            log("onDisConnectCallChanged isDisConnected:" + isDisConnected);
        }
    };

    @Override
    public String getName() {
        return "连接服务端";
    }
}
